package com.jetlion.servicebind2;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.jetlion.servicebind2.IStu;

public class MainActivity extends AppCompatActivity {

    private IStu mBinder;

    private Boolean isBind;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            if (iBinder != null) {
                mBinder = (IStu) iBinder;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bindBtn = findViewById(R.id.bind_btn);
        Button getMsgBtn = findViewById(R.id.getMsg_btn);
        Button unbindBtn = findViewById(R.id.unbind_btn);

        bindBtn.setOnClickListener(new View.OnClickListener() {

            /**
             * 由此可见，在Android5.0中增加了对intent的判断，因为intent是通过设置action得到的，
             * 因此没有Component对象的实例，也没有包名，故而报错。原因找到，增加了一个设置包名的步骤，
             * 而且需要是App的包名，而不是Service类所在包的包名，即可顺利解决，代码如下：
             * @param view
             */
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.service.AIDLService");
                intent.setPackage("com.jetlion.servicebind2");
                isBind = bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
            }
        });

        getMsgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBinder != null) {
                    try {
                        String stuName = mBinder.getStuName();
                        String stuNo = mBinder.getStuNo();
                        Log.i("MainActivity", stuName + ":" + stuNo);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        unbindBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isBind) {
                    unbindService(serviceConnection);
                    isBind = false;
                }
            }
        });

    }
}